<template>
  <div class="app-container">
    <div class="page-header">
      
    </div>

    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card enhanced-card">
      <div class="card-header">
        <div class="header-icon-container">
          <i class="el-icon-search header-icon"></i>
        </div>
        <span class="header-title">工单筛选</span>
      </div>
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px" class="enhanced-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6" :lg="5" :xl="5">
            <el-form-item label="表单编号" prop="formNo" class="form-item-enhanced">
              <el-input
                v-model="queryParams.formNo"
                placeholder="请输入表单编号"
                clearable
                @keyup.enter.native="handleQuery"
                class="enhanced-input"
                maxlength="20"
              >
                <i slot="prefix" class="el-input__icon el-icon-tickets"></i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="5" :xl="5">
            <el-form-item label="叶片编码" prop="bladeCode" class="form-item-enhanced">
              <el-input
                v-model="queryParams.bladeCode"
                placeholder="请输入叶片编码"
                clearable
                @keyup.enter.native="handleQuery"
                class="enhanced-input"
                maxlength="64"
              >
                <i slot="prefix" class="el-input__icon el-icon-cpu"></i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="5" :xl="5">
            <el-form-item label="创建者" prop="createBy" class="form-item-enhanced">
              <el-input
                v-model="queryParams.createBy"
                placeholder="请输入创建者"
                clearable
                @keyup.enter.native="handleQuery"
                class="enhanced-input"
              >
                <i slot="prefix" class="el-input__icon el-icon-user"></i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="5" :xl="5">
            <el-form-item label="状态" prop="status" class="form-item-enhanced">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="enhanced-select">
                <el-option label="正常" value="0"/>
                <el-option label="已修改" value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="4" :xl="4" class="form-buttons">
            <el-button type="primary" icon="el-icon-search" class="action-btn" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" class="reset-btn" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 顶部工具栏 -->
    <el-card shadow="hover" class="toolbar-card enhanced-card">
      <div class="card-header">
        <div class="header-icon-container">
          <i class="el-icon-document header-icon"></i>
        </div>
        <span class="header-title">工单管理</span>
      </div>

      <div class="toolbar-section">
        <div class="toolbar-buttons">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['repair:form:add']"
            class="action-btn primary-btn"
          >新增工单
          </el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['repair:form:remove']"
            :class="{ 'action-btn danger-btn': true, 'disabled-btn': multiple }"
          >批量删除
          </el-button>
        </div>

        <div class="stats-container">
          <div class="stat-card total">
            <div class="stat-icon-container">
              <i class="el-icon-document stat-icon"></i>
            </div>
            <div class="stat-content">
              <div class="stat-label">工单总数</div>
              <div class="stat-value">{{ total }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="formList"
          @selection-change="handleSelectionChange"
          stripe
          style="width: 100%; table-layout: auto;"
          class="enhanced-table"
          :header-cell-style="{background: '#f5f7fa', color: '#303133', fontWeight: 'bold'}"
          :row-style="{cursor: 'pointer'}"

        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="表单编号" align="center" prop="formNo" class-name="bold-column"/>
          <el-table-column label="叶片编码" align="center" prop="bladeCode" class-name="bold-column"/>
          <el-table-column label="裂纹图片" align="center" >
            <template slot-scope="scope">
              <div v-if="scope.row.imagePaths && scope.row.imagePaths.length > 0" class="image-preview">
                <el-image
                  style="width: 80px; height: 60px; cursor: pointer; border-radius: 4px;"
                  :src="getFullImageUrl(scope.row.imagePaths[0])"
                  :preview-src-list="scope.row.imagePaths.map(p => getFullImageUrl(p))"
                  fit="cover"
                  hide-on-click-modal
                  :z-index="3000"
                >
                  <div slot="error" class="image-slot">
                    <el-icon>
                      <Picture/>
                    </el-icon>
                  </div>
                </el-image>
              </div>
              <div v-else class="no-image">
                <el-icon>
                  <Picture/>
                </el-icon>
                <span>无图片</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="创建者" align="center" width="120">
            <template slot-scope="scope">
              <!-- 判断创建者是否为 admin，若是则显示管理员 -->
              <span>{{ scope.row.createBy === 'admin' ? '管理员' : scope.row.createBy }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span class="time-text">{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新者" align="center" width="120">
            <template slot-scope="scope">
              <!-- 判断更新者是否为 admin，若是则显示管理员 -->
              <span>{{ scope.row.updateBy === 'admin' ? '管理员' : scope.row.updateBy }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
            <template #default="scope">
              <span class="time-text">{{ parseTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="100">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === '0' ? 'success' : 'warning'"
                effect="dark"
                class="status-tag"
                style="width: 80px; justify-content: center;"
              >
                {{ scope.row.status === '0' ? '正常' : '已修改' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :width="isMobile ? 150 : 200">
            <template slot-scope="scope">
              <el-tooltip content="查看详情" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  class="action-btn detail"
                  @click.stop="handleDetail(scope.row)"
                  v-hasPermi="['repair:form:query']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="编辑工单" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  class="action-btn edit"
                  @click.stop="handleUpdate(scope.row)"
                  v-hasPermi="['repair:form:edit']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除工单" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  class="action-btn delete"
                  @click.stop="handleDelete(scope.row)"
                  v-hasPermi="['repair:form:remove']"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-container">
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>

    <!-- 添加或修改工单对话框 -->
    <el-dialog :title="title"
               :visible.sync="open" width="1000px"
               append-to-body
               class="custom-dialog">
      <div class="dialog-body-scrollable">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-tabs v-model="activeTab" class="custom-tabs">
            <!-- 裂纹修复信息 -->
            <el-tab-pane label="裂纹修复" name="first" ref="basicInfoTab">
              <div class="form-section">
                <div class="section-header">
                  <i class="el-icon-document"></i>
                  <span>工单基本信息</span>
                </div>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="表单编号" prop="formNo" class="enhanced-form-item">
                      <el-input
                        v-model="form.formNo"
                        placeholder="请输入表单编号"
                        class="enhanced-input"
                        maxlength="20"
                        :disabled="!isAdd"
                      >
                        <i slot="prefix" class="el-input__icon el-icon-tickets"></i>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="叶片编码" prop="bladeCode" class="enhanced-form-item">
                      <el-input
                        v-model="form.bladeCode"
                        placeholder="请输入叶片编码"
                        class="enhanced-input"
                        maxlength="64"
                      >
                        <i slot="prefix" class="el-input__icon el-icon-cpu"></i>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="裂纹描述" prop="crackDescription" class="enhanced-form-item">
                      <el-input
                        v-model="form.crackDescription"
                        type="textarea"
                        :rows="4"
                        placeholder="请详细描述叶片裂纹信息..."
                        class="enhanced-textarea"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="深裂纹尺寸" prop="deepCrackSize" class="enhanced-form-item">
                      <el-input
                        v-model="form.deepCrackSize"
                        placeholder="请输入深裂纹尺寸"
                        class="enhanced-input"
                        maxlength="128"
                      >
                        <i slot="prefix" class="el-input__icon el-icon-ruler"></i>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <div class="form-section">
                <div class="section-header">
                  <i class="el-icon-picture"></i>
                  <span>裂纹图片</span>
                </div>

                <el-row>
                  <el-col :span="24">
                    <el-form-item class="enhanced-form-item">
                      <el-upload
                        action=""
                        list-type="picture-card"
                        :auto-upload="false"
                        :file-list="fileList"
                        :on-change="handleImageChange"
                        :on-remove="handleImageRemove"
                        :before-upload="beforeImageUpload"
                        :multiple="true"
                        :limit="5"
                        ref="upload"
                        class="image-uploader"
                      >
                        <div class="custom-upload-tip">
                          <i class="el-icon-plus upload-icon"></i>

                        </div>
                        <div slot="tip" class="el-upload__tip">
                          <p>支持格式：JPG/PNG(最多上传5张图片)</p>
                        </div>
                      </el-upload>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>

            <!-- 参数设置 -->
            <el-tab-pane label="参数设置" name="second">
              <div class="form-section">
                <div class="section-header">
                  <i class="el-icon-setting"></i>
                  <span>参数配置</span>
                </div>

                <el-tabs type="border-card" class="inner-tabs">
                  <el-tab-pane label="叶片裂纹参数">
                    <div class="param-header">
                      <span>裂纹参数设置</span>
                    </div>
                    <parameter-editor
                      ref="crackParams"
                      :is-view-mode="isDetail"
                      :params="crackParams"
                      paramType="crack"
                      @params-change="crackParams = $event"
                    />
                  </el-tab-pane>

                  <el-tab-pane label="工艺参数">
                    <div class="param-header">
                      <span>工艺参数设置</span>
                    </div>
                    <parameter-editor
                      ref="techParams"
                      :is-view-mode="isDetail"
                      :params="techParams"
                      paramType="tech"
                      @params-change="techParams = $event"
                    />
                  </el-tab-pane>
                </el-tabs>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>

      <!-- 底部操作按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button :loading="btnLoading" type="primary" @click="submitForm" class="primary-btn">保 存</el-button>
        <el-button @click="cancel" class="cancel-btn">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 工单详情对话框 -->
    <el-dialog title="工单详情" :visible.sync="detailOpen" width="70%" append-to-body :z-index="1000"
               class="detail-dialog"
    >
      <div class="detail-container">
        <!-- 基本信息卡片 -->
        <el-card shadow="never" class="detail-card">
          <div class="card-header">
            <i class="el-icon-document header-icon"></i>
            <span class="header-title">基本信息</span>
          </div>

          <div class="detail-grid">
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">表单编号</span>
                <span class="detail-value">{{ detailForm.formNo }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">叶片编码</span>
                <span class="detail-value">{{ detailForm.bladeCode || '暂无' }}</span>
              </div>
            </div>

            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">创建者</span>
                <span class="detail-value">{{ detailForm.createBy === 'admin' ? '管理员' : detailForm.createBy }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">深裂纹尺寸</span>
                <span class="detail-value">{{ detailForm.deepCrackSize || '暂无' }}</span>
              </div>
            </div>

            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">创建时间</span>
                <span class="detail-value">{{ parseTime(detailForm.createTime) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">更新者</span>
                <span class="detail-value">{{ detailForm.updateBy === 'admin' ? '管理员' : detailForm.updateBy }}</span>
              </div>
            </div>

            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">更新时间</span>
                <span class="detail-value">{{ parseTime(detailForm.updateTime) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">状态</span>
                <span class="detail-value">
                <el-tag :type="detailForm.status === '0' ? 'success' : 'warning'"
                        effect="dark"
                        class="status-tag"
                        style="width: 80px;
                        justify-content: center">
                  {{ detailForm.status === '0' ? '正常' : '已修改' }}
                </el-tag>
              </span>
              </div>

            </div>
          </div>
        </el-card>

        <!-- 裂纹描述卡片 -->
        <el-card shadow="never" class="detail-card">
          <div class="card-header">
            <i class="el-icon-tickets header-icon"></i>
            <span class="header-title">裂纹描述</span>
          </div>
          <div class="description-content">
            {{ detailForm.crackDescription || '暂无描述信息' }}
          </div>
        </el-card>

        <!-- 裂纹图片卡片 -->
        <el-card shadow="never" class="detail-card">
          <div class="card-header">
            <i class="el-icon-picture header-icon"></i>
            <span class="header-title">裂纹图片</span>
          </div>
          <div class="detail-value image-gallery">
            <div v-if="detailForm.imagePaths && detailForm.imagePaths.length > 0" class="image-container">
              <el-image
                v-for="(path, index) in detailForm.imagePaths"
                :key="index"
                :src="getFullImageUrl(path)"
                :preview-src-list="detailForm.imagePaths.map(p => getFullImageUrl(p))"
                fit="cover"
                class="gallery-image"
              >
                <template #error>
                  <div class="image-error">
                    <i class="el-icon-picture-outline"></i>
                    <span>加载失败</span>
                  </div>
                </template>
              </el-image>
            </div>
            <div v-else class="no-images">
              <i class="el-icon-picture-outline"></i>
              <span>暂无图片</span>
            </div>
          </div>
        </el-card>

        <!-- 叶片裂纹参数卡片 -->
        <el-card shadow="never" class="detail-card">
          <div class="card-header">
            <i class="el-icon-data-analysis header-icon"></i>
            <span class="header-title">叶片裂纹参数</span>
          </div>
          <el-table :data="detailCrackParams" border style="width: 100%" class="param-table">
            <el-table-column prop="paramName" label="参数名称" width="180" align="center" header-align="center"/>
            <el-table-column prop="paramValue" label="参数值" align="center" header-align="center"/>
            <el-table-column prop="unit" label="单位" width="100" align="center" header-align="center"/>
          </el-table>
        </el-card>

        <!-- 工艺参数卡片 -->
        <el-card shadow="never" class="detail-card">
          <div class="card-header">
            <i class="el-icon-setting header-icon"></i>
            <span class="header-title">工艺参数</span>
          </div>
          <el-table :data="detailTechParams" border style="width: 100%" class="param-table">
            <el-table-column prop="paramName" label="参数名称" width="180" align="center" header-align="center"/>
            <el-table-column prop="paramValue" label="参数值" align="center" header-align="center"/>
            <el-table-column prop="unit" label="单位" width="100" align="center" header-align="center"/>
          </el-table>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listForm, getForm, addForm, updateForm, delForm, uploadImage } from '@/api/repair/repairBlade'
import ParameterEditor from './components/ParameterEditor.vue'
import dayjs from 'dayjs'

export default {
  name: 'BladeRepairForm',
  components: { ParameterEditor },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 按钮加载状态
      btnLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 正常状态工单数
      normalCount: 0,
      // 已修改状态工单数
      modifiedCount: 0,
      // 工单表格数据
      formList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 当前激活的标签页
      activeTab: 'first',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        formNo: undefined,
        bladeCode: undefined,
        createBy: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        status: '0',
        imagePaths: [], // 数组存储多个图片路径
        bladeCode: undefined, // 叶片编码
        deepCrackSize: undefined // 深裂纹尺寸
      },
      // 详情表单
      detailForm: {},
      // 文件列表
      fileList: [],
      // 裂纹参数
      crackParams: [],
      // 工艺参数
      techParams: [],
      // 详情裂纹参数
      detailCrackParams: [],
      // 详情工艺参数
      detailTechParams: [],
      isAdd: false,
      // 表单校验
      rules: {
        formNo: [
          { required: true, message: '表单编号不能为空', trigger: 'blur' },
          { max: 20, message: '表单编号输入超出限制', trigger: 'blur' }
        ],
        bladeCode: [
          { required: true, message: '叶片编码不能为空', trigger: 'blur' },
          { max: 64, message: '叶片编码输入超出限制', trigger: 'blur' }
        ],
        crackDescription: [
          { required: true, message: '裂纹描述不能为空', trigger: 'blur' }
        ],
        deepCrackSize: [
          { required: true, message: '深裂纹尺寸不能为空', trigger: 'blur' },
          { max: 128, message: '深裂纹尺寸输入超出限制', trigger: 'blur' }
        ]

      },
      // 状态统计
      statusStats: {
        normal: 0,
        modified: 0
      },
      // 上传状态
      uploading: false,
      isDetail: false,
      // 当前日期
      currentDate: dayjs().format('YYYY年MM月DD日'),
      isMobile: false

    }
  },
  created() {
    this.getList();
    // 初始化时获取状态统计
    this.fetchStatusStats();
    window.addEventListener('resize', this.checkMobile);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkMobile);
  },
  methods: {
    /** 查询工单列表 */
    getList() {
      this.loading = true;
      listForm(this.queryParams).then(response => {
        if (response && response.code === 200) {
          this.formList = response.rows;
          this.total = response.total;
        } else {
          this.$modal.msgError('数据加载失败: ' + (response.msg || '未知错误'));
        }
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        this.$modal.msgError('数据加载失败: 网络错误');
      });
    },
    /** 检查是否为移动端 */
    checkMobile() {
      this.isMobile = window.innerWidth < 768;
    },
    /** 获取状态统计数据 */
    fetchStatusStats() {
      // 这里应该调用API获取整个系统的状态统计数据
      // 假设我们有一个名为getStatusStats的API方法
      getStatusStats().then(response => {
        if (response.code === 200) {
          this.statusStats = {
            normal: response.data.normalCount,
            modified: response.data.modifiedCount
          };
        } else {
          console.error('获取状态统计失败:', response.msg);
        }
      }).catch(error => {
        console.error('获取状态统计失败:', error);
      });

      if (!this.hasStatsAPI) {
        listForm({ pageNum: 1, pageSize: 10000 }).then(response => {
          if (response.code === 200) {
            const allForms = response.rows;
            this.statusStats = {
              normal: allForms.filter(item => item.status === '0').length,
              modified: allForms.filter(item => item.status === '1').length
            };
          }
        });
      }
    },

    /**获取图片路径 */
    getFullImageUrl(path) {
      if (!path) return ''
      if (path.startsWith('http')) return path
      const gatewayBaseUrl = 'http://localhost:8080'
      path = path.replace('\\', '/')
      if (path.includes('/pictures/')) {
        return `${gatewayBaseUrl}${path}`
      }
      return `${gatewayBaseUrl}/pictures/${path}`
    },
    /**时间格式器 */
    parseTime(time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        formNo: undefined,
        bladeCode: undefined,
        crackDescription: undefined,
        deepCrackSize: undefined,
        imagePaths: [],
        status: '0'
      }

      this.crackParams = []
      this.techParams = []
      this.fileList = []
      this.isDetail = false

      this.$nextTick(() => {
        if (this.$refs.crackParams) {
          this.$refs.crackParams.reset()
        }
        if (this.$refs.techParams) {
          this.$refs.techParams.reset()
        }
      })

      this.resetForm('form')
      this.activeTab = 'first'
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isAdd = true
      this.isDetail = false
      this.reset()
      this.crackParams = []
      this.techParams = []
      this.form.formNo = `${dayjs().format('YYYYMMDD')}-`
      this.open = true
      this.title = '新增工单'
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.isDetail = true
      const id = row.id
      getForm(id).then(response => {
        if (response.code === 200 && response.data) {
          this.detailForm = response.data.form || {}
          this.detailCrackParams = response.data.crackParams || []
          this.detailTechParams = response.data.techParams || []

          if (this.detailForm.imagePaths) {
            this.detailForm.imagePaths = this.detailForm.imagePaths.map(p => {
              return this.getFullImageUrl(p)
            })
          }

          this.detailOpen = true
        } else {
          this.$message.error('获取详情失败: ' + (response.msg || '未知错误'))
        }
      }).catch(error => {
        this.$message.error('获取详情失败: ' + (error.message || '未知错误'))
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isAdd = false
      this.isDetail = false
      this.reset()
      const id = row.id

      getForm(id).then(response => {
        if (response.code === 200 && response.data) {
          this.form = {
            ...response.data.form,
            id: response.data.form.id
          }

          this.crackParams = response.data.crackParams || []
          this.techParams = response.data.techParams || []

          this.crackParams.forEach((item, index) => {
            if (item.sort === undefined || item.sort === null) {
              item.sort = index
            }
          })

          this.techParams.forEach((item, index) => {
            if (item.sort === undefined || item.sort === null) {
              item.sort = index
            }
          })

          if (response.data.form.imagePaths && response.data.form.imagePaths.length > 0) {
            this.fileList = response.data.form.imagePaths.map((url, index) => {
              return {
                uid: index,
                name: `裂纹图片-${index + 1}`,
                url: this.getFullImageUrl(url),
                status: 'success',
                rawPath: url
              }
            })
          } else {
            this.fileList = []
          }

          this.open = true
          this.title = '修改工单'

        } else {
          this.$message.error('获取工单数据失败: ' + (response.msg || '未知错误'))
        }
      }).catch(error => {
        this.$message.error('获取工单数据失败: ' + (error.message || '未知错误'))
        console.error('获取工单数据失败:', error)
      })
    },
    /** 确认按钮 */
    async submitForm() {
      // 在表单校验开始前就禁用按钮
      this.btnLoading = true;
      this.$refs['form'].validate(async valid => {
        if (valid) {
          try {
            if (this.activeTab !== 'first') {
              const hasBasicInfo = this.form.formNo && this.form.bladeCode && this.form.crackDescription && this.form.deepCrackSize
              if (!hasBasicInfo) {
                this.activeTab = 'first'
                this.$nextTick(() => {
                  this.$message({
                    message: '请先填写完整的工单基本信息',
                    type: 'warning',
                    customClass: 'warning-message',
                    duration: 3000
                  })
                  if (!this.form.formNo) {
                    this.$refs.form.validateField('formNo')
                  }
                  if (!this.form.bladeCode) {
                    this.$refs.form.validateField('bladeCode')
                  }
                  if (!this.form.crackDescription) {
                    this.$refs.form.validateField('crackDescription')
                  }
                  if (!this.form.deepCrackSize) {
                    this.$refs.form.validateField('deepCrackSize')
                  }
                })
                return
                }
                if (!this.form.formNo || !this.form.bladeCode || !this.form.crackDescription || !this.form.deepCrackSize) {
                  this.$message({
                    message: '请填写完整的工单基本信息',
                    type: 'error',
                    customClass: 'error-message',
                    duration: 3000
                  })
                  return
                }
              }

              const imageUrls = await this.uploadAllImages()
              this.form.imagePaths = imageUrls

              const crackParams = this.$refs.crackParams?.getParams() || []
              const techParams = this.$refs.techParams?.getParams() || []

              if (crackParams.length === 0 && techParams.length === 0) {
                this.$message({
                  message: '至少填写一种参数类型（裂纹参数或工艺参数）',
                  type: 'error',
                  customClass: 'error-message'
                })
                this.fileList.forEach(file => {
                  console.log('图片预览 URL:', file.url);
                });
                // 未找到原因，暂时先清空图片
                this.$nextTick(() => {
                  if (this.$refs.upload) {
                    // 重置 el-upload 组件状态
                    this.$refs.upload.clearFiles();
                    this.$refs.upload.fileList = this.fileList;
                  }
                  this.$forceUpdate();
                });
                return
              }

              crackParams.forEach((param, index) => {
                if (param.sort === undefined || param.sort === null) {
                  param.sort = index
                }
              })

              techParams.forEach((param, index) => {
                if (param.sort === undefined || param.sort === null) {
                  param.sort = index
                }
              })

              const formData = {
                form: this.form,
                param: {
                  crackParams: crackParams,
                  techParams: techParams
                }
              }

              let apiCall
              let successMsg
              if (this.form.id != null) {
                apiCall = updateForm(formData)
                successMsg = '修改成功'
              } else {
                apiCall = addForm(formData)
                successMsg = '新增成功'
              }
              apiCall.then(response => {
                if (response.code === 200) {
                  this.$message.success(successMsg)
                  this.open = false
                  this.getList()
                } else {
                  this.$message.error(response.msg || '操作失败')
                }
              }).catch(error => {
                handleFormError(error)
              }).finally(() => {
                this.btnLoading = false;
              })
            } catch (error) {
              this.$message({
                message: error.message || '图片上传失败，请重试',
                type: 'error',
                customClass: 'error-message',
                duration: 3000
              })
              this.btnLoading = false;
            }
          } else {
            this.$message({
              message: '请检查表单中的必填项',
              type: 'error',
              customClass: 'error-message',
              duration: 3000
            })
            this.btnLoading = false;
          }
        })
      },


    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids
      this.$confirm(`确认删除选中的${ids.length}个工单？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delForm(ids.join(',')).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    /** 图片上传前校验 */
    beforeImageUpload(file) {
      const isImage = file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('只能上传JPG/PNG格式的图片!')
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB!')
      }

      return isImage && isLt5M
    },

    /** 处理图片选择 */
    handleImageChange(file, fileList) {
      this.fileList = fileList
    },

    /** 处理图片移除 */
    handleImageRemove(file, fileList) {
      this.fileList = fileList
    },

    /** 上传所有图片 */
    async uploadAllImages() {
      if (this.fileList.length === 0) {
        return []
      }

      this.uploading = true
      const uploadPromises = []
      const uploadedImages = []

      for (const file of this.fileList) {
        if (file.status === 'success' && file.rawPath) {
          uploadedImages.push(file.rawPath)
          continue
        }

        if (file.raw) {
          try {
            const response = await uploadImage(file.raw)
            if (response.code === 200) {
              file.status = 'success'
              file.url = response.data
              uploadedImages.push(response.data)
            } else {
              throw new Error(response.msg || '图片上传失败')
        }
          } catch (error) {
            console.error('图片上传失败:', error)
            file.status = 'fail'
            this.$message.error(`图片 ${file.name} 上传失败`)
          }
      }
    }

      this.uploading = false
      return uploadedImages
    },

    /** 行点击事件
    handleRowClick(row, column, event) {
      if (column.label !== '操作') {
        this.handleDetail(row)
    */
  }
}
</script>

<style lang="scss" scoped>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');

* {
  box-sizing: border-box;
  font-family: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}

.app-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  position: relative;
  overflow: hidden;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  background: linear-gradient(135deg, #4c76c3 0%, #a9b3c2 100%);
  color: white;

  .header-content {
    padding: 20px 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      display: flex;
      align-items: center;

      i {
        margin-right: 12px;
        font-size: 28px;
        color: #FFD700;
      }
    }

    .header-stats {
      display: flex;
      gap: 20px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 15px;
        font-weight: 500;

        i {
          font-size: 18px;
          color: #FFD700;
        }
      }
    }
  }

  .header-banner {
    padding: 10px 30px;
    background: rgba(0, 0, 0, 0.1);

    .banner-text {
      font-size: 16px;
      font-weight: 300;
      letter-spacing: 1px;
      opacity: 0.9;
    }
  }
}

.enhanced-card {
  border-radius: 10px;
  border: none;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    align-items: center;
    padding: 18px 20px;
    background: linear-gradient(135deg, #f8f9fc 0%, #e9ecef 100%);
    border-bottom: 1px solid #eaeaea;

    .header-icon-container {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: linear-gradient(135deg, #409EFF 0%, #1e88e5 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 12px;

      .header-icon {
        font-size: 18px;
        color: white;
      }
    }

    .header-title {
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }
}

.search-card {
  margin-bottom: 20px;

  .enhanced-form {
    padding: 15px 20px 5px;

    .form-item-enhanced {
      margin-bottom: 20px;

      ::v-deep .el-form-item__label {
        font-weight: 500;
        color: #34495e;
      }
    }

    .enhanced-input {
      ::v-deep .el-input__inner {
        border-radius: 6px;
        border: 1px solid #dcdfe6;
        transition: border-color 0.3s;

        &:focus {
          border-color: #409EFF;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }
    }

    .enhanced-select {
      width: 100%;

      ::v-deep .el-input__inner {
        border-radius: 6px;
      }
    }

    .form-buttons {
      display: flex;
      justify-content: flex-start;
      align-items: flex-end;
      gap: 10px;
      padding-top: 30px;

      .action-btn {
        padding: 10px 16px;
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s;
        font-size: 14px;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
      }

      .reset-btn {
        background: #f5f7fa;
        border-color: #dcdfe6;
        color: #606266;
        padding: 10px 16px;
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s;
        font-size: 14px;

        &:hover {
          background: #e4e7ed;
          border-color: #c0c4cc;
        }
      }
    }
  }
}

.toolbar-card {
  .toolbar-section {
    padding: 15px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .toolbar-buttons {
      margin-bottom: 0px;

      .action-btn {
        padding: 10px 20px;
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        &.primary-btn {
          background: linear-gradient(135deg, #409EFF 0%, #1e88e5 100%);
          color: white;
          border: none;

          &:hover {
            background: linear-gradient(135deg, #1e88e5 0%, #bfd2ee 100%);
          }
        }

        &.danger-btn {
          background: linear-gradient(135deg, #ff6b6b 0%, #f03e3e 100%);
          color: white;
          border: none;

          &:hover {
            background: linear-gradient(135deg, #f03e3e 0%, #c92a2a 100%);
          }
        }
        &.disabled-btn {
          background: linear-gradient(135deg, #ffb8b8 0%, #f88787 100%);
          opacity: 0.6;
          cursor: not-allowed;

          &:hover {
            background: linear-gradient(135deg, #f88787 0%, #ec9038 100%);
          }
        }
      }
    }

    .stats-container {
      display: flex;
      gap: 15px;
      margin-bottom: 0px;
      flex-wrap: wrap;

      .stat-card {
        flex: 1;
        min-width: 200px;
        background: white;
        border-radius: 8px;
        padding: 15px;
        display: flex;
        align-items: center;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        transition: transform 0.3s;

        &:hover {
          transform: translateY(-3px);
        }

        .stat-icon-container {
          width: 50px;
          height: 50px;
          border-radius: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;

          .stat-icon {
            font-size: 24px;
            color: white;
          }
        }

        .stat-content {
          .stat-label {
            font-size: 14px;
            color: #7f8c8d;
            margin-bottom: 5px;
          }

          .stat-value {
            font-size: 24px;
            font-weight: 700;
            color: #2c3e50;
          }
        }

        &.total {
          border-left: 4px solid #3498db;

          .stat-icon-container {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
          }
        }

        &.normal {
          border-left: 4px solid #2ecc71;

          .stat-icon-container {
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
          }
        }

        &.modified {
          border-left: 4px solid #f39c12;

          .stat-icon-container {
            background: linear-gradient(135deg, #f39c12 0%, #d35400 100%);
          }
        }
      }
    }
  }

  .table-container {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    overflow: hidden;
  }

  .enhanced-table {
    ::v-deep th {
      background: #f8fafc !important;
      color: #2c3e50;
      font-weight: 600;
    }

    ::v-deep .el-table__row {
      transition: background 0.3s;

      &:hover {
        background-color: #f5f9ff !important;
      }
    }

    .bold-column {
      font-weight: 500;
      color: #34495e;
    }

    .status-tag {
      font-weight: 500;
      padding: 5px 0;
      border-radius: 12px;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      box-sizing: border-box;
    }

    .time-text {
      color: #7f8c8d;
      font-size: 13px;
    }

    .action-btn {
      font-size: 16px;
      padding: 5px;
      transition: all 0.2s;

      &.detail {
        color: #3498db;

        &:hover {
          color: #2980b9;
          transform: scale(1.2);
        }
      }

      &.edit {
        color: #f39c12;

        &:hover {
          color: #d35400;
          transform: scale(1.2);
        }
      }

      &.delete {
        color: #e74c3c;

        &:hover {
          color: #c0392b;
          transform: scale(1.2);
        }
      }
    }

    .image-preview {
      display: flex;
      justify-content: center;
    }

    .no-image {
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #95a5a6;

      i {
        font-size: 24px;
        margin-bottom: 5px;
      }

      span {
        font-size: 12px;
      }
    }
  }

  .pagination-container {
    margin-top: -5px;
    padding: 20px 0;
    display: flex;
    justify-content:right;
  }
}

.custom-dialog {
  border-radius: 12px;
  overflow: hidden;

  ::v-deep .el-dialog__header {
    background: linear-gradient(135deg, #f8f9fc 0%, #e9ecef 100%);
    padding: 15px 20px;
    border-bottom: 1px solid #eaeaea;

    .el-dialog__title {
      font-weight: 600;
      color: #2c3e50;
    }
  }

  .dialog-body-scrollable {
    max-height: 75vh;
    overflow-y: auto;
    padding: 20px;

    .custom-tabs {
      ::v-deep .el-tabs__nav-wrap::after {
        background-color: #eaeaea;
      }

      ::v-deep .el-tabs__item {
        font-weight: 500;
        color: #7f8c8d;

        &.is-active {
          color: #409EFF;
        }
      }
    }

    .form-section {
      margin-bottom: 25px;
      padding: 15px;
      background: #f9fbfd;
      border-radius: 8px;
      border: 1px solid #eaeef5;

      .section-header {
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px dashed #e0e6ed;
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: 600;
        color: #2c3e50;

        i {
          margin-right: 10px;
          color: #409EFF;
          font-size: 18px;
        }
      }

      .enhanced-form-item {
        margin-bottom: 20px;

        ::v-deep .el-form-item__label {
          width: 80%;
          font-weight: 500;
          color: #34495e;
        }
        .el-upload__tip{
          width: 180px;
          font-size:10px;
        }

        .enhanced-input {
          ::v-deep .el-input__inner {
            border-radius: 6px;
            transition: border-color 0.3s;

            &:focus {
              border-color: #409EFF;
              box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
            }
          }
        }

        .enhanced-textarea {
          ::v-deep .el-textarea__inner {
            width: 100%;
            border-radius: 6px;
            transition: border-color 0.3s;

            &:focus {
              border-color: #409EFF;
              box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
            }
          }
        }
      }

      .image-uploader {
        ::v-deep .el-upload {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          background: #fafafa;
          transition: border-color 0.3s;

          &:hover {
            border-color: #409EFF;
          }

          .upload-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
          }

          .upload-icon {
            font-size: 28px;
            color: #8c939d;
          }

          .upload-tip {
            margin-top: 5px;
            color: #606266;
            font-size: 12px;
          }
        }
      }
    }

    .inner-tabs {
      border-radius: 8px;

      .param-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 15px;

        span {
          font-weight: 500;
          color: #2c3e50;
        }
      }
    }
  }

  .dialog-footer {
    padding: 15px 20px;
    background: #f8fafc;
    border-top: 1px solid #eaeaea;
    display: flex;
    justify-content: center;
    gap: 10px;

    .cancel-btn, .primary-btn {
      padding: 10px 20px;
      border-radius: 6px;
      font-weight: 500;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .primary-btn {
      background: linear-gradient(135deg, #409EFF 0%, #1e88e5 100%);
      border: none;
      color: white;

      &:hover {
        background: linear-gradient(135deg, #1e88e5 0%, #0d6efd 100%);
      }
    }
  }
}

.detail-dialog {
  border-radius: 12px;

  ::v-deep .el-dialog__header {
    background: linear-gradient(135deg, #f8f9fc 0%, #e9ecef 100%);
    padding: 15px 20px;
    border-bottom: 1px solid #eaeaea;

    .el-dialog__title {
      font-weight: 600;
      color: #2c3e50;
    }
  }

  .detail-container {
    max-height: 70vh;
    overflow-y: auto;
    padding: 0 10px;

    .detail-card {
      margin-bottom: 20px;
      border-radius: 8px;
      border: 1px solid #ebeef5;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

      .card-header {
        display: flex;
        align-items: center;
        padding: 15px 20px;
        background: #f8fafc;
        border-bottom: 1px solid #eaeaea;

        .header-icon {
          font-size: 18px;
          color: #409EFF;
          margin-right: 10px;
        }

        .header-title {
          font-size: 16px;
          font-weight: 600;
          color: #2c3e50;
        }
      }

      .detail-grid {
        padding: 20px;

        .detail-row {
          display: flex;
          margin-bottom: 15px;

          .detail-item {
            flex: 1;
            display: flex;

            .detail-label {
              width: 100px;
              font-weight: 500;
              color: #7f8c8d;
            }

            .detail-value {
              flex: 1;
              color: #34495e;
              font-weight: 500;

              .status-tag {
                font-weight: 500;
                padding: 3px 10px;
                border-radius: 12px;
                display: flex;
                align-items: flex-start;
                justify-content: center;
                line-height: 1.2;
              }
            }
          }
        }
      }

      .description-content {
        padding: 20px;
        color: #34495e;
        line-height: 1.6;
        background: #f9fbfd;
        border-radius: 0 0 8px 8px;
      }

      .image-gallery {
        padding: 15px;
        background: #f9fbfd;
        border-radius: 0 0 8px 8px;

        .image-container {
          display: flex;
          flex-wrap: wrap;
          gap: 15px;

          .gallery-image {
            width: 120px;
            height: 90px;
            border-radius: 6px;
            overflow: hidden;
            border: 1px solid #eaeaea;
            transition: transform 0.3s;

            &:hover {
              transform: scale(1.05);
              box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            }
          }
        }

        .no-images {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 30px;
          color: #95a5a6;

          i {
            font-size: 40px;
            margin-bottom: 10px;
          }
        }
      }

      .param-table {
        border-radius: 0 0 8px 8px;
        overflow: hidden;

        ::v-deep th {
          background: #f8fafc !important;
          font-weight: 600;
          color: #2c3e50;
        }
      }
    }
  }
}
</style>
